#include <iostream>
#include <stdlib.h>
#ifdef _WIN32
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#else
#include <sys/socket.c>
#endif

using namespace std;

SOCKET      server_socket, client_socket;
sockaddr_in server_addr, client_addr;

#define BUFFSIZE 512
char input_buf[BUFFSIZE];
char read_buf[BUFFSIZE];
char send_buf[BUFFSIZE];

int main(int argc, char const *argv[])
{
    cout << "Server Start!\r\n";

    WSADATA wsadata;
    if (WSAStartup(MAKEWORD(2, 2), &wsadata) != 0)
    {
        cout << "Load WSA Sokcet Failed!\r\n";
        system("pause");
        return 0;
    }

    server_socket               = socket(AF_INET, SOCK_STREAM, 0); //初始话Socket
    server_addr.sin_addr.s_addr = inet_addr("localhost");          //初始化地址-IP
    server_addr.sin_family      = AF_INET;                         //初始化地址-协议
    server_addr.sin_port        = htons(1111);                     //初始化地址-端口

    bind(server_socket, (sockaddr *)&server_addr, sizeof(server_addr));
    listen(server_socket, 5);
    while (true)
    {
        cout << "Listen Start!\r\n";
        int sin_size;
        client_socket = accept(server_socket, (sockaddr *)&client_addr, &sin_size);
        if (client_socket != INVALID_SOCKET)
        {
            cout << "Connect Success!\r\n";
            cout << "Input something\r\n";
            cin >> input_buf;
            send(client_socket, input_buf, sizeof(input_buf), 0);
            recv(client_socket, read_buf, sizeof(read_buf), 0);
            cout << "Recv from Client : " << read_buf << endl;
        }
        else
        {
            cout << "Accept Failed!\r\n";
        }
    }
    closesocket(client_socket);
    closesocket(server_socket);
    return 0;
}
